import json
import requests

from langchain_core.tools import tool
from langgraph.prebuilt import ToolNode
from langchain_core.messages import AIMessage

@tool
def fetch_real_time_info(query):
    """Get real-time Internet information"""

    url = "https://google.serper.dev/search"

    payload = json.dumps({
        "q": query,
        "num": 1,
    })

    headers = {
        'X-API-KEY': '22a84d67009121271e4a5eb21d809e11d3bc8d45',
        'Content-Type': 'application/json'
    }

    response = requests.post(url, headers=headers, data=payload)

    data = json.loads(response.text)  # 将返回的JSON字符串转换为字典

    if 'organic' in data:
        return json.dumps(data['organic'],  ensure_ascii=False)  # 返回'organic'部分的JSON字符串
    else:
        return json.dumps({"error": "No organic results found"},  ensure_ascii=False)  # 如果没有'organic'键，返回错误信息

# resp = fetch_real_time_info("长江有多长")
# print(resp)

@tool
def get_weather(location):
    """Call to get the current weather."""
    if location.lower() in ["北京"]:
        return "北京的温度是16度，天气晴朗。"
    elif location.lower() in ["重庆"]:
        return "重庆的温度是32度，天气晴朗。"
    else:
        return "不好意思，并未查询到具体的天气信息。"


tools = [fetch_real_time_info,get_weather]
tool_node = ToolNode(tools)

message_with_multiple_tool_calls = AIMessage(
    content="",
    tool_calls=[
        {
            "name":"fetch_real_time_info",
            "args":{"query":"小米汽车"},
            "id":"tool_call_id",
            "type":"tool_call"
        },
        {
            "name":"get_weather",
            "args":{"location":"重庆"},
            "id":"tool_call_id2",
            "type":"tool_call"
        }
    ]
)

resp = tool_node.invoke({"messages":[message_with_multiple_tool_calls]})
print(resp)

